package com.itpan.Utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itpan.Entity.Employee;
import com.itpan.Service.EmployeeService;

import java.util.ArrayList;
import java.util.List;

public class EmployeeExcelListener extends AnalysisEventListener<Employee> {


    private final EntityValidate entityValidate;
    private final EmployeeService employeeService;
    private List<Employee> employeeList = new ArrayList<>();



    public EmployeeExcelListener(EntityValidate entityValidate, EmployeeService employeeService) {
        this.entityValidate = entityValidate;
        this.employeeService = employeeService;
    }

    @Override
    public void invoke(Employee employee, AnalysisContext context) {
        // 校验数据是否有效
        if (isValidEmployee(employee) && isAreadyRegister(employee) && entityValidate.isValidateOfEmployee(employee)) {
            employeeList.add(employee);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 读取结束后的操作，可以进行批量保存或其他处理
        if (!employeeList.isEmpty()) {
            employeeService.saveEmployees(employeeList);
        }
    }

    private boolean isValidEmployee(Employee employee) {
        // 检查每个字段是否为null或空
        return  employee.getEmployeeName() != null
                && employee.getEmployeePassword() != null
                && employee.getEmployeeLevel() != null
                && employee.getEmployeePhone() != null
                && employee.getSalary() != null
                && employee.getRemark() != null;
    }

    /*
    判断该字段的id是否已经注册

     */

    private boolean isAreadyRegister(Employee employee){
        Employee em = employeeService.getEmployeeById(employee.getEmployeeID());
        if(em!=null){
            return false;
        }else return true;
    }
}
